/**
 * 
 */
package com.sl.log;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import com.alibaba.fastjson.JSON;
import com.sl.util.ReflectionUtils;

/**
 * @author lunshi
 * TODO
 * @创建时间 2020 2020年3月10日 下午3:57:45
 * @email:shilun217@qq.com
 */
@MethodAdvice(assignableTypes= {MethodLogFlag.class})
public class PrintLogMethodInterceptor implements MethodInterceptor{
	private Logger logger = LoggerFactory.getLogger(PrintLogMethodInterceptor.class);
	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		long startTime = System.currentTimeMillis();
		String methodName = invocation.getMethod().getName();
	    Object[] arguments = invocation.getArguments();
	    MethodLogPrint typeAnnotation = ReflectionUtils.getAnnotation(invocation.getThis().getClass(), MethodLogPrint.class);
	    MethodLogPrint[] methodAnnotations = invocation.getMethod().getAnnotationsByType(MethodLogPrint.class);
	    PrintLogType printLogType=null;
	    if ((methodAnnotations != null) && (methodAnnotations.length > 0)) {
	    		printLogType=methodAnnotations[0].printType();	
	      } else if (typeAnnotation != null) {
	    	  printLogType=typeAnnotation.printType();
	      }
	      Object result = invocation.proceed();
	      long expendTime=System.currentTimeMillis()-startTime;
	      if(null!=printLogType) {
		    	if(printLogType==PrintLogType.PARAMTERS) {
		    		if(arguments!=null) {
		    			logger.info("\\執行方法: {},参数：{}",methodName,JSON.toJSONString(arguments));
		    		}
		    	}if(printLogType==PrintLogType.EXPEND_TIME){
		    		logger.info("\\執行方法: {},耗时：{}",methodName,JSON.toJSONString(arguments),expendTime);
		    	}else{
		    		if(arguments!=null) {
			    		logger.info("\\執行方法: {},耗时：{}",methodName,JSON.toJSONString(arguments),expendTime);
		    		}else {
			    		logger.info("\\執行方法: {},耗时：{},参数：{}",methodName,expendTime,JSON.toJSONString(arguments));
		    		}
		    	}
		    }
	      return result;
	}

}
